//
//  MainViewController.m
//  OrderingMerchantsSide
//
//  Created by iOS on 2018/9/19.
//  Copyright © 2018年 mls. All rights reserved.
//

#import "MainViewController.h"
#import "MSNavigationController.h"
#import <Lottie/Lottie.h>

@interface MainViewController ()

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *jsonFilePath = [ms_pathOfDocument stringByAppendingPathComponent:@"main.json"];
    
    NSData *data = [NSData dataWithContentsOfFile:jsonFilePath];
    
    if (!data)
    {
        jsonFilePath = [[NSBundle mainBundle] pathForResource:@"main" ofType: @"json"];
        data = [NSData dataWithContentsOfFile:jsonFilePath];
    }
    
    NSArray<NSDictionary *> *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
    NSMutableArray *jsonFiles = [NSMutableArray array];
    NSMutableArray *VCs = [NSMutableArray array];
    for (NSDictionary *dict in arr)
    {
        [jsonFiles addObject:dict[@"image"]];
        [VCs addObject:[self controllerWithDict:dict]];
    }
    
    MSTabBar *tabBar = [[MSTabBar alloc] init];
    tabBar.barTintColor = UIColor.whiteColor;
    tabBar.backgroundColor = UIColor.whiteColor;
    tabBar.lotJsonFileArr = jsonFiles;
    
    [self setValue:tabBar forKey:@"tabBar"];
    
    self.tabBar.selectionIndicatorImage = UIImage.new;
    self.tabBar.backgroundImage = UIImage.new;
    self.tabBar.shadowImage = [UIImage ms_imageWithColor:UIColor.whiteColor];
    self.viewControllers = VCs;
    [self.tabBar setBarTintColor:[UIColor whiteColor]];
    [RACObserve(self, selectedIndex) subscribeNext:^(id  _Nullable x) {
        
        [self playAnimation:self.selectedIndex];
    }];
    
    /*
    NSMutableArray *VCs = [NSMutableArray array];
    for (NSDictionary *dict in arr)
    {
        [VCs addObject:[self controllerWithDict:dict]];
    }
    
    self.tabBar.selectionIndicatorImage = [[UIImage alloc] init];
    self.viewControllers = VCs;
    */
    [self.tabBar setBarTintColor:[UIColor whiteColor]];
}

- (UINavigationController *)controllerWithDict:(NSDictionary *)info
{
    UIViewController *VC = [[NSClassFromString(info[@"className"]) alloc] init];
    VC.tabBarItem.image = MS_IMAGE_NAMED(info[@"image"]);
    VC.tabBarItem.selectedImage = MS_IMAGE_NAMED(info[@"selectedImage"]);
    VC.tabBarItem.imageInsets = UIEdgeInsetsMake(2, 0, -3, 3);
    
    VC.title = info[@"title"];
    VC.tabBarItem.titlePositionAdjustment = UIOffsetMake(0,
                                                         -2);
    [VC.tabBarItem setTitleTextAttributes:@{NSFontAttributeName : MS_SYSTEM_FONT_OF_SIZE(10),
                                            NSForegroundColorAttributeName : MS_HEX_COLOR(0x9FA5AF)}
                                 forState:UIControlStateNormal];
    [VC.tabBarItem setTitleTextAttributes:@{NSFontAttributeName : MS_SYSTEM_FONT_OF_SIZE(10),
                                            NSForegroundColorAttributeName : MS_HEX_COLOR(0xDC1424)}
                                 forState:UIControlStateHighlighted];
     
    
    return [[MSNavigationController alloc] initWithRootViewController:VC];
}

- (void)playAnimation:(NSInteger)selectedIndex
{
    for (UIView *view in self.tabBar.subviews)
    {
        if ([view isKindOfClass:[LOTAnimationView class]])
        {
            [((LOTAnimationView *)view) stop];
        }
    }
    
    LOTAnimationView *LOTView = [self.tabBar viewWithTag:100+selectedIndex];
    
    if (LOTView.animationProgress == 0) {
        
        [LOTView playFromProgress:0
                       toProgress:0.5
                   withCompletion:^(BOOL animationFinished) {
            
        }];
    }
}


- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    NSInteger index = [self.tabBar.items indexOfObject:item];
    [self playAnimation:index];
    /*
    NSMutableArray<UIView *> *tabBarBtns = [NSMutableArray array];
    
    [self.tabBar.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:NSClassFromString(@"UITabBarButton")])
        {
            [tabBarBtns addObject:obj];
        }
    }];
    
    // 抖动效果
    CABasicAnimation*pulse = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    pulse.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    pulse.duration = 0.1;
    pulse.repeatCount = 1;
    pulse.autoreverses = YES;
    pulse.fromValue = [NSNumber numberWithFloat:0.7];
    pulse.toValue = [NSNumber numberWithFloat:1.3];
    [[tabBarBtns[index] layer] addAnimation:pulse forKey:nil];
     */
}

@end


@implementation MSTabBar

- (void)layoutSubviews
{
    [super layoutSubviews];
    int count = (int)self.lotJsonFileArr.count;
    CGFloat width = CGRectGetWidth(self.frame) / count;
    if (self.subviews.count >= count * 2)
    {
        return;
    }
    for (int i = 0; i < count; i++)
    {
        LOTAnimationView *LOTView = [LOTAnimationView animationNamed:self.lotJsonFileArr[i]];
        LOTView.tag = 100 + i;
        LOTView.userInteractionEnabled = NO;
        LOTView.contentMode = UIViewContentModeScaleAspectFill;
        LOTView.cacheEnable = NO;
        CGFloat w = 150;
        CGFloat h = 118;
        CGFloat height = width * h / w;
        CGRect LOTViewFrame = CGRectMake(i * width, MIN(-20 * MS_ADAPTATION_RATIO, 49 - height - 2), width, height);
        [LOTView setFrame:LOTViewFrame];
        [self addSubview:LOTView];
        if (i == 0)
        {
            [LOTView playToProgress:0.5 withCompletion:^(BOOL animationFinished) {
                
            }];
        }
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
